angular.module('vote').controller('managePrizeCtrl', ['$scope', '$uibModalInstance', '$http', 'id', function ($scope, $uibModalInstance, $http, id) {
    $scope.vote = {
        prizes: []
    };
    $scope.prizes = {};
    $scope.selectedAll = false;
    $scope.onInit = function () {
        $http.get(ctx + '/vote/getPrizes?voteId=' + id).then(function (resp) {
            console.log(resp);
            $scope.vote = resp.data.vote;
            $scope.prizes = angular.copy(resp.data.prizes);
            for (var i = 0; i < $scope.prizes.length; i++) {
                var prize = $scope.prizes[i];
                for (var j = 0; j < $scope.vote.prizes.length; j++) {
                    var pri = $scope.vote.prizes[j];
                    if (prize.id == pri.id)
                        prize.selected = true;
                }
            }
            var flag = true;
            for (var i = 0; i < $scope.prizes.length; i++) {
                var prize = $scope.prizes[i];
                if (!prize.selected) {
                    flag = false;
                    break;
                }
            }
            $scope.selectedAll = flag;
        });
    }
    $scope.onInit();
    $scope.ok = function () {
        var selected = [];
        for (var i = 0; i < $scope.prizes.length; i++) {
            var prize = $scope.prizes[i];
            if (prize.selected) {
                selected.push(prize);
            }
        }
        $scope.vote.prizes = selected;
        $http.post(ctx + '/vote/save', $scope.vote).then(function (resp) {
            $uibModalInstance.close();
        });
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

    $scope.selectAll = function () {
        for (var i = 0; i < $scope.prizes.length; i++) {
            var prize = $scope.prizes[i];
            prize.selected = $scope.selectedAll;
        }

    }
    $scope.selectOne = function () {
        var flag = true;
        for (var i = 0; i < $scope.prizes.length; i++) {
            var prize = $scope.prizes[i];
            if (!prize.selected) {
                flag = false;
                $scope.selectedAll = false;
                break;
            }
        }
        if (flag) $scope.selectedAll = true;
    }


}]);